package com.lab303.powerproject.util;


import com.lab303.powerproject.entity.*;
import com.lab303.powerproject.repository.TemperatureRepository;
import com.lab303.powerproject.service.DeviceService;
import com.lab303.powerproject.service.RelationshipService;
import com.lab303.powerproject.service.impl.ElectricityPriceServiceImpl;
import com.lab303.powerproject.service.impl.PredictDataServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.rmi.Remote;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class StrategyGenerator {

    private static final Logger LOG = LoggerFactory.getLogger(StrategyGenerator.class);
    private MinCost mc;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private RelationshipService edgeService;
    @Autowired
    private ElectricityPriceServiceImpl epsi;

    @Autowired
    private PredictDataServiceImpl pdsi;

    @Autowired
    private TemperatureRepository temperatureRepository;


    Device getDeviceById(int x) {
        return deviceService.findDeviceById(x);
    }

    HashMap<Integer, double[]> getFlowFrDb() {
        return pdsi.getAllPredictData(); //每个用能设备24小时需要的能量,根据机器学习模型获取
    }

    List<Relationship> getFrDb() {
        return edgeService.findAllRelationship();
    }

    double[] getPriceFrDb() {
        //获取每个小时的电价；
        return epsi.getPriceEveryHour();
    }

    public Map<String, Object> getStrategy() {
        try {
            Map ans = doStrategy();

            //高龙修改


            LOG.info("策略执行成功");
            return ans;
        } catch (Exception e) {
            LOG.error("exception happens when generate strategy");
            Map ans = new HashMap<String, Object>();
            ans.put("rc", "1");
            return ans;
        }
    }

    public Map<String, Object> doStrategy() {
        HashMap<Integer, Integer> hs = new HashMap<>();//建立设备id到图谱中编号的一个映射
        HashMap<Integer, Integer> g2dev = new HashMap<>();//建立图谱中编号到设备id的一个映射
        HashSet<Integer> useDeivce = new HashSet<>();
        HashMap<Integer, Integer> pp = new HashMap<>();//记录产能设备指向产能设备的映射关系
        HashMap<Integer, TreeSet<Integer>> produce = new HashMap<>();////记录每个产能设备指向的设备
        HashMap<Integer, TreeSet<Integer>> produceTo = new HashMap<>();////记录某个产能设备修改后指向的节点
        ArrayList<Integer> energyDeivce = new ArrayList<>();
        List<Relationship> edgeSet = getFrDb();//从库中查询出边关系的集合
        System.out.println("取出边关系");
        LOG.info("取出边关系");
        Set<Integer> nodes = new TreeSet<Integer>();
        int id = 0;
        for (int i = 0; i < edgeSet.size(); ++i) {
            nodes.add(edgeSet.get(i).getDeviceFrom());
            nodes.add(edgeSet.get(i).getDeviceTo());
            if (!hs.containsKey(edgeSet.get(i).getDeviceFrom())) {
                g2dev.put(id, edgeSet.get(i).getDeviceFrom());
                hs.put(edgeSet.get(i).getDeviceFrom(), id++);
            }
            if (!hs.containsKey(edgeSet.get(i).getDeviceTo())) {
                g2dev.put(id, edgeSet.get(i).getDeviceTo());
                hs.put(edgeSet.get(i).getDeviceTo(), id++);
            }
        }

        mc = new MinCost(nodes.size() * 24 + 2);//一个节点扩展成24个节点，对应24个小时,+源+汇
        double[] priceSet = getPriceFrDb();
        HashMap<Integer, double[]> flowSet = getFlowFrDb();
        Iterator flowiter = flowSet.entrySet().iterator();
        int flow = 0;
        //1:产能设备，2:储能设备.3:用能设备
        Iterator iter = hs.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) iter.next();
            Device device = getDeviceById(entry.getKey());
            String gap = device.getWorkTime();
            int start = Integer.parseInt(gap.split("-")[0]);
            int end = Integer.parseInt(gap.split("-")[1]);
            HashSet<Integer> workTime = new HashSet<Integer>();
            for (int kk = start; kk <= end; ++kk) {
                workTime.add(kk);
            }
            if (device.getDeviceType().getTypeId() == 1) {
                for (int k = 0; k < 24; ++k) {
                    if (!workTime.contains(k)) continue;
                    mc.addEdge(nodes.size() * 24, 24 * entry.getValue() + k, (int) device.getPower(), 0);//建立源点到所有产能设备的有向边
                }
            } else if (device.getDeviceType().getTypeId() == 2) {

                for (int p = 1; p < 24; ++p) {//储能设备的最大cap理论上为设备总共的蓄能能力，而不是某个小时的蓄能能力，这里特别注意
                    if (!workTime.contains(p)) continue;
                    //mc.addEdge(24*entry.getValue()+ p - 1,24*entry.getValue()+ p,getThreshold(entry.getKey()),0);
                    mc.addEdge(24 * entry.getValue() + p - 1, 24 * entry.getValue() + p, (int) device.getPower(), 0);
                }
            } else if (device.getDeviceType().getTypeId() == 3) {
                useDeivce.add(entry.getKey());
                if (device.getIsPredicted() == 0) continue;//没有经过数据预测处理的用能设备不纳入到决策生成过程中来
                for (int q = 0; q < 24; ++q) {
                    if (!workTime.contains(q)) continue;
                    System.out.println(24 * entry.getValue() + q + " ");
                    mc.addEdge(24 * entry.getValue() + q, nodes.size() * 24 + 1, flowSet.get(entry.getKey()) == null ? 0 : (int) flowSet.get(entry.getKey())[q], 0);
                    flow += flowSet.get(entry.getKey()) == null ? 0 : (int) flowSet.get(entry.getKey())[q];
                }//建立所有用能设备到汇点的有向边
            }
        }

        for (int j = 0; j < edgeSet.size(); ++j) {
            Device device = getDeviceById(edgeSet.get(j).getDeviceFrom());
            Device todevice = getDeviceById(edgeSet.get(j).getDeviceTo());
            int fr = hs.get(edgeSet.get(j).getDeviceFrom());//图谱上对应的起点id
            int to = hs.get(edgeSet.get(j).getDeviceTo());//图谱上对应的终点id
            double conv = device.getConversionRate() / 10000;
            double ratio = (100 - edgeSet.get(j).getLossRate()) / 100;//提供单位能量需要消耗的电能
            float power = device.getPower();
            String gap = device.getWorkTime();
            int start = Integer.parseInt(gap.split("-")[0]);
            int end = Integer.parseInt(gap.split("-")[1]);
            HashSet<Integer> workTime = new HashSet<Integer>();
            for (int kk = start; kk <= end; ++kk) {
                workTime.add(kk);
            }
            if (device.getDeviceType().getTypeId() == 1 && todevice.getDeviceType().getTypeId() == 2) {
                System.out.println(device.getDeviceId() + " " + todevice.getDeviceId());
                System.out.println(fr + " " + to);
                System.out.println("+++");
                if (device.getDeviceType().getTypeId() == 1) {
                    if (produce.containsKey(fr)) {
                        produce.get(fr).add(to);
                    } else {
                        produce.put(fr, new TreeSet<Integer>());
                        produce.get(fr).add(to);
                    }
                }
                /*a:储能设备到用能设备转换率，0.95
                 * b:储能设备每小时的损耗率
                 * n:用电最高峰,设置为15:00
                 * t:当前的时间
                 * r:产能设备到用能设备的转换率
                 * e:电量到能量的转换比，设置为1
                 * */
                double a = 0.95;
                double b = 0.05;
                double e = ratio;
                double r = conv;
                int n = 15;
                for (int i = 0; i < 24; ++i) {
                    if (!workTime.contains(i)) continue;
                    mc.addEdge(24 * fr + i, 24 * to + i, (int) power, (int) (priceSet[i] / (a * r * e * (Math.pow(1 - b, Math.abs(i - n))))));
                }

            } else if (device.getDeviceType().getTypeId() == 2) {//如果是储能设备
                for (int i = 0; i < 24; ++i) {//储能设备的最大cap理论上为设备总共的蓄能能力，而不是某个小时的蓄能能力，这里特别注意
                    if (!workTime.contains(i)) continue;
                    mc.addEdge(24 * fr + i, 24 * to + i, (int) power, 0);
                }
            } else {
                System.out.println(device.getDeviceId() + " " + todevice.getDeviceId());
                System.out.println(fr + " " + to);
                System.out.println("+++");
                if (device.getDeviceType().getTypeId() == 1) {
                    if (produce.containsKey(fr)) {
                        produce.get(fr).add(to);
                    } else {
                        produce.put(fr, new TreeSet<Integer>());
                        produce.get(fr).add(to);
                    }
                }
                if (device.getDeviceType().getTypeId() == 1 && todevice.getDeviceType().getTypeId() == 1) continue;
                for (int i = 0; i < 24; ++i) {
                    if (!workTime.contains(i)) continue;
                    mc.addEdge(24 * fr + i, 24 * to + i, (int) power, (int) (priceSet[i] / conv / ratio));//创建好了设备图结构
                }
            }
        }

        for (int j = 0; j < edgeSet.size(); ++j) {
            Device device = getDeviceById(edgeSet.get(j).getDeviceFrom());
            Device todevice = getDeviceById(edgeSet.get(j).getDeviceTo());
            int fr = hs.get(edgeSet.get(j).getDeviceFrom());//图谱上对应的起点id
            int to = hs.get(edgeSet.get(j).getDeviceTo());//图谱上对应的终点id
            double conv = device.getConversionRate() / 10000;
            double ratio = (100 - edgeSet.get(j).getLossRate()) / 100;//提供单位能量需要消耗的电能
            float power = device.getPower();
            if (device.getDeviceType().getTypeId() == 1 && todevice.getDeviceType().getTypeId() == 1) {
                String gap = device.getWorkTime();
                int start = Integer.parseInt(gap.split("-")[0]);
                int end = Integer.parseInt(gap.split("-")[1]);
                HashSet<Integer> workTime = new HashSet<Integer>();
                for (int kk = start; kk <= end; ++kk) {
                    workTime.add(kk);
                }
                pp.put(fr, to);
                TreeSet<Integer> trees = produce.get(to);
                Iterator treesSet = trees.iterator();
                while (treesSet.hasNext()) {
                    int node = (int) treesSet.next();
                    if (produce.get(fr).contains(node)) continue;//如果已经指向直接continue
                    if (produceTo.containsKey(fr)) {
                        produceTo.get(fr).add(node);
                    } else {
                        produceTo.put(fr, new TreeSet<Integer>());
                        produceTo.get(fr).add(node);
                    }
                    for (int k = 0; k < 24; ++k) {
                        if (!workTime.contains(k)) continue;
                        mc.addEdge(24 * fr + k, 24 * node + k, (int) power, (int) (priceSet[k] / conv / ratio));
                        //产能设备指向产能设备时，让 fr 指向 to指向的设备
                    }
                }

            }
        }
        int source = nodes.size() * 24;//源点编号；
        int target = nodes.size() * 24 + 1;//汇点编号
        int rc = mc.getResult(source, target, flow);//生成策略
        if (rc == -1) {
            System.out.println("找不到满足要求的供能策略!");
            LOG.error("找不到满足要求的供能策略!");
        } else {
            HashMap<Integer, TreeSet<Integer>> openTime = new HashMap<>();//工况
            HashMap<Integer, TreeSet<Integer>> openStrategy = new HashMap<>();//图谱策略
            System.out.println("++++++++++++++++++++");
            for (int i = 0; i < nodes.size() * 24; ++i) {
                List<int[]> ans = mc.query(i);
                if (ans.size() != 0) {
                    if (useDeivce.contains(g2dev.get(i / 24))) continue;
                    if (openTime.containsKey(g2dev.get(i / 24))) {
                        openTime.get(g2dev.get(i / 24)).add(i % 24);
                    } else {
                        openTime.put(g2dev.get(i / 24), new TreeSet<Integer>());
                        openTime.get(g2dev.get(i / 24)).add(i % 24);
                    }
                    for (int j = 0; j < ans.size(); ++j) {
                        if (ans.get(j)[0] == nodes.size() * 24 || ans.get(j)[0] == nodes.size() * 24 + 1 || ans.get(j)[0] / 24 == i / 24)
                            continue;//对源点、汇点不做处理
                        if (openStrategy.containsKey(g2dev.get(i / 24))) {
                            openStrategy.get(g2dev.get(i / 24)).add(g2dev.get(ans.get(j)[0] / 24));
                        } else {
                            openStrategy.put(g2dev.get(i / 24), new TreeSet<Integer>());
                            openStrategy.get(g2dev.get(i / 24)).add(g2dev.get(ans.get(j)[0] / 24));
                        }
                    }
                }
            }
            StringBuilder gongkuang = new StringBuilder();
            Iterator openTimeiter = openTime.entrySet().iterator();
            Iterator openStrategyiter = openStrategy.entrySet().iterator();

            System.out.println("生成工况");
            int cnt = 0;
            while (openTimeiter.hasNext()) {
                Map.Entry<Integer, TreeSet<Integer>> entry = (Map.Entry<Integer, TreeSet<Integer>>) openTimeiter.next();
                TreeSet<Integer> lis = (TreeSet<Integer>) entry.getValue();
                Device device = getDeviceById(entry.getKey());
                if (device.getDeviceType().getTypeId() != 2) {
                    System.out.println(device.getDeviceName() + " ");
                    Iterator itSet = lis.iterator();
                    StringBuilder initStr = new StringBuilder(device.getDeviceName() + "     ");
                    char ch[] = new char[24];
                    for (int i = 0; i < 24; ++i) ch[i] = ' ';
       /*         int start = 0;
                while (itSet.hasNext()) {
                    Object obj = itSet.next();
                    if (start != 0) initStr.append("-");
                    initStr.append(String.valueOf(obj));
                    System.out.print((int) obj + " ");
                    start++;
                }
                if (cnt != 0) gongkuang.append(",");
                gongkuang.append(initStr.toString());
                cnt++;
                System.out.println();*/
                    while (itSet.hasNext()) {
                        Object obj = itSet.next();
                        ch[(int) obj] = (char) ('a' + (int) obj);
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int q = 0; q < 24; ++q) {
                        sb.append(ch[q]);
                    }
                    String str[] = sb.toString().split(" ");
                    int flag = 0;
                    for (int n = 0; n < str.length; ++n) {
                        String tmp = str[n];
                        if (tmp.length() == 0) continue;
                        if (tmp.length() == 1) {
                            if (flag != 0) initStr.append("、");
                            initStr.append((tmp.charAt(0) - 'a' < 10 ? "0" + String.valueOf(tmp.charAt(0) - 'a') : String.valueOf(tmp.charAt(0) - 'a')) + ":00~" + (tmp.charAt(0) - 'a' + 1 < 10 ? "0" + String.valueOf(tmp.charAt(0) - 'a' + 1) : String.valueOf(tmp.charAt(0) - 'a' + 1)) + ":00");
                        } else {
                            char start = tmp.charAt(0);
                            char end = tmp.charAt(tmp.length() - 1);
                            if (flag != 0) initStr.append("、");
                            initStr.append((start - 'a' < 10 ? "0" + String.valueOf(start - 'a') : String.valueOf(start - 'a')) + ":00~" + (end - 'a' + 1 < 10 ? "0" + String.valueOf(end - 'a' + 1) : String.valueOf(end - 'a' + 1)) + ":00");
                        }
                        flag++;
                    }
                    if (cnt != 0) gongkuang.append(",");
                    gongkuang.append(initStr.toString());
                    cnt++;
                } else {
                    System.out.println(device.getDeviceName() + " ");
                    Iterator itSet = lis.iterator();
                    StringBuilder initStr = new StringBuilder(device.getDeviceName() + "     ");
                    char ch[] = new char[24];
                    for (int i = 0; i < 24; ++i) ch[i] = ' ';
       /*         int start = 0;
                while (itSet.hasNext()) {
                    Object obj = itSet.next();
                    if (start != 0) initStr.append("-");
                    initStr.append(String.valueOf(obj));
                    System.out.print((int) obj + " ");
                    start++;
                }
                if (cnt != 0) gongkuang.append(",");
                gongkuang.append(initStr.toString());
                cnt++;
                System.out.println();*/
                    while (itSet.hasNext()) {
                        Object obj = itSet.next();
                        ch[(int) obj] = (char) ('a' + (int) obj);
                    }
                    StringBuilder sb = new StringBuilder();
                    for (int q = 0; q < 24; ++q) {
                        sb.append(ch[q]);
                    }
                    String str[] = sb.toString().split(" ");
                    int flag = 0;
                    for (int n = 0; n < str.length; ++n) {
                        String tmp = str[n];
                        if (tmp.length() == 0) continue;
                        if (tmp.length() == 1) {
                            if (flag != 0) initStr.append("、");
                            initStr.append((tmp.charAt(0) - 'a' < 10 ? "0" + String.valueOf(tmp.charAt(0) - 'a') : String.valueOf(tmp.charAt(0) - 'a')) + ":00~" + (tmp.charAt(0) - 'a' + 1 < 10 ? "0" + String.valueOf(tmp.charAt(0) - 'a' + 1) : String.valueOf(tmp.charAt(0) - 'a' + 1)) + ":00");
                        } else {
                            char start = tmp.charAt(0);
                            char end = tmp.charAt(tmp.length() - 1);
                            if (flag != 0) initStr.append("、");
                            if (end - 'a' <= 7) {
                                initStr.append((start - 'a' < 10 ? "0" + String.valueOf(start - 'a') : String.valueOf(start - 'a')) + ":00~" + (end - 'a' + 1 < 10 ? "0" + String.valueOf(end - 'a' + 1) : String.valueOf(end - 'a' + 1)) + ":00" + "蓄能");
                            } else if (start - 'a' >= 7) {
                                initStr.append((start - 'a' < 10 ? "0" + String.valueOf(start - 'a') : String.valueOf(start - 'a')) + ":00~" + (end - 'a' + 1 < 10 ? "0" + String.valueOf(end - 'a' + 1) : String.valueOf(end - 'a' + 1)) + ":00" + "放能");
                            } else {
                                initStr.append(String.valueOf(start - 'a') + ":00~" + "7:00蓄能、7:00~" + (end - 'a' + 1 < 10 ? "0" + String.valueOf(end - 'a' + 1) : String.valueOf(end - 'a' + 1)) + ":00放能");
                            }
                            //initStr.append((start - 'a' < 10 ? "0" + String.valueOf(start - 'a') : String.valueOf(start - 'a')) + ":00~" + (end - 'a' + 1 < 10 ? "0" + String.valueOf(end - 'a' + 1) : String.valueOf(end - 'a' + 1)) + ":00");
                        }
                        flag++;
                    }
                    if (cnt != 0) gongkuang.append(",");
                    gongkuang.append(initStr.toString());
                    cnt++;
                }
            }
            System.out.println("生成图谱");

         /*       //debug block
                System.out.println("                debug block 1 #               ");
                Iterator ppiter = pp.entrySet().iterator();
                while (ppiter.hasNext()) {
                    Map.Entry<Integer, Integer> ppentry = (Map.Entry<Integer, Integer>) ppiter.next();
                    System.out.println(ppentry.getKey() + " " + ppentry.getValue());
                }

                Iterator produceToIter = produceTo.entrySet().iterator();
                while (produceToIter.hasNext()) {
                    Map.Entry<Integer, TreeSet<Integer>> produceToentry = (Map.Entry<Integer, TreeSet<Integer>>) produceToIter.next();
                    TreeSet<Integer> ss = (TreeSet<Integer>) produceToentry.getValue();
                    Iterator itSet = ss.iterator();
                    while (itSet.hasNext()){
                        System.out.println(produceToentry.getKey() + " " + itSet.next());
                    }

                }
                System.out.println("                debug block 1#                ");*/
            Map res = new HashMap<String, Object>();
            StringBuilder path = new StringBuilder();
            HashSet<Integer> retNodes = new HashSet<>();
            StringBuilder Nodes = new StringBuilder();

            while (openStrategyiter.hasNext()) {
                Map.Entry<Integer, TreeSet<Integer>> entry = (Map.Entry<Integer, TreeSet<Integer>>) openStrategyiter.next();
                TreeSet<Integer> lis = (TreeSet<Integer>) entry.getValue();
                Iterator itSet = lis.iterator();
                while (itSet.hasNext()) {
                    Object obj = itSet.next();
                    //System.out.println(hs.get(entry.getKey()) + " " + hs.get((int) obj));
                    if (pp.containsKey(hs.get(entry.getKey())) && produceTo.get(hs.get(entry.getKey())).contains((hs.get((int) obj)))) {
                        path.append(String.valueOf(entry.getKey()) + '#' + String.valueOf(g2dev.get(pp.get(hs.get(entry.getKey())))) + ",");
                        path.append(String.valueOf(g2dev.get(pp.get(hs.get(entry.getKey())))) + '#' + String.valueOf(obj) + ",");
                        retNodes.add(entry.getKey());
                        retNodes.add(g2dev.get(pp.get(hs.get(entry.getKey()))));
                        retNodes.add((int) obj);
                        System.out.println(getDeviceById(entry.getKey()).getDeviceName() + "->" + getDeviceById(g2dev.get(pp.get(hs.get(entry.getKey())))).getDeviceName() + "->" + getDeviceById((int) obj).getDeviceName());
                    } else {
                        path.append(String.valueOf(entry.getKey()) + '#' + String.valueOf(obj) + ",");
                        retNodes.add(entry.getKey());
                        retNodes.add((int) obj);
                        System.out.println(getDeviceById(entry.getKey()).getDeviceName() + "->" + getDeviceById((int) obj).getDeviceName());
                    }
                }
            }

            Iterator<Integer> it = retNodes.iterator();
            int t = 0;
            while (it.hasNext()) {
                if (t != 0) Nodes.append(",");
                Nodes.append(String.valueOf(it.next()));
                t++;
            }

            Map ans = new HashMap<String, Object>();
            String temp = path.toString();
            String str = temp.substring(0, temp.length() - 1);
            ans.put("rc", "0");
            ans.put("path", str.split(","));
            ans.put("node", Nodes.toString().split(","));
            ans.put("gongkuang", gongkuang.toString().split(","));
            System.out.println("path:" + str);
            System.out.println("gongkaung:" + gongkuang.toString());
            System.out.println("Node:" + Nodes.toString());
            return ans;
        }
        Map ans = new HashMap<String, Object>();
        ans.put("rc", "1");
        return ans;
    }

    /**
     * 根据历史工况归纳出工况规律，预测未来工况
     *
     * @param shuiXuNengCap     水蓄能每小时的蓄能能力
     * @param reBengToDiBan     地源热泵直供末端能效比
     * @param shuiXuNengToDiBan 地缘热泵通过水蓄能蓄热供给末端能效比
     * @param price             峰谷平电价
     * @param coefficient       水蓄能放能系数
     * @param fallingTem        不供暖时一个小时温度下降的度数
     * @param risingTem         开启主机直控时一个小时温度上升的度数
     * @param comfortTem        冬季舒适温度
     * @param holidayBeginTime  节假日开始时间
     * @param holidayEndTime    节假日结束时间
     * @param requirement       末端需求量
     * @param remain            水蓄能累计剩余量
     * @param now               运行策略时间
     * @return 工况
     */
    public Map<String, Object> doGenerateStrategy(float shuiXuNengCap,
                                                  float reBengToDiBan,
                                                  float shuiXuNengToDiBan,
                                                  float[] price,
                                                  float coefficient,
                                                  float fallingTem,
                                                  float risingTem,
                                                  float comfortTem,
                                                  String holidayBeginTime,
                                                  String holidayEndTime,
                                                  float[] requirement,
                                                  float remain,
                                                  Date now) throws IOException, ParseException {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd");
        Date holidayBeginDate = simpleDateFormat.parse(holidayBeginTime);
        Date holidayEndDate = simpleDateFormat.parse(holidayEndTime);

        int[] shuiXuNeng = new int[24];     //水蓄能开启状态量
        int[] zhuJiZhiGong = new int[24];   //主机直供开启状态量

        float[] shuiXuNengXu = new float[24];
        float[] shuiXuNengFang = new float[24];
        float[] zhuJi = new float[24];
        float[] solar = new float[24];

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(now);
        calendar.add(calendar.DATE, 1);

        float maxPrice = Float.MIN_VALUE;  //最高电价
        float minPrice = Float.MAX_VALUE;  //最低电价
        float middlePrice = 0;             //平段电价
        for (int i = 0; i < price.length; i++) {
            if (maxPrice < price[i]) maxPrice = price[i];
            else if (minPrice < price[i]) middlePrice = price[i];
            else minPrice = price[i];
        }

        float A = maxPrice / minPrice;
        float B = maxPrice / middlePrice;
        float C = middlePrice / middlePrice;
        float D = reBengToDiBan / shuiXuNengToDiBan;

        float re = 0;   //剩余量

        float xuNeng = remain; //水蓄能蓄能量，加上前一天剩下的

        if (now.before(holidayEndDate) && now.after(holidayBeginDate)) {  //长假
            for (int i = 0; i < requirement.length; i++) {
                if (requirement[i] > 0) {
                    zhuJiZhiGong[i] = 1;
                    zhuJi[i] = 300;
                }
            }
        } else {  //非长假
            if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {  //明天是周日
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DATE);
                /*Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(now);
                calendar1.set(Calendar.HOUR, calendar1.get(Calendar.HOUR) - 1);// 前一小时
                String time = new SimpleDateFormat("MM-dd HH").format(calendar1.getTime());*/
                String time = month+"-"+day+" 22";
                Temperature temperatureData = temperatureRepository.findTemperatureByDateTime(time);
                float temperature = comfortTem;
                if (temperatureData!=null){
                    temperature = Float.parseFloat(temperatureData.getTemperatureData());
                }
                temperature-=2;
                for (int i = 23; i < 7 ||i==23; i = (i + 1) % 24) {
                    if (requirement[i] > 0) {
                        zhuJiZhiGong[i] = 1;
                        zhuJi[i] = requirement[i];
                    }
                }
                for (int j = 22;j<=23;j++){
                    if (zhuJiZhiGong[j] == 1) {
                        temperature += risingTem;
                    } else {
                        temperature -= fallingTem;
                    }
                }
                for (int i = 0; i < zhuJiZhiGong.length - 1 ; i = (i + 1) % 24) {
                    if (zhuJiZhiGong[i] == 1) {
                        temperature += risingTem;
                    } else {
                        temperature -= fallingTem;
                    }
                }
                if (temperature < comfortTem) {
                    float v = 8 * risingTem;
                    if (temperature + v < comfortTem) {
                        float v1 = 5 * fallingTem;
                        float v2 = comfortTem + v - v1;
                        for (int i = 17; i >= 11; i--) {
                            v2 += risingTem;
                            if (v2 >= comfortTem) {
                                zhuJi[i] = 700;
                                zhuJiZhiGong[i] = 1;
                                break;
                            } else {
                                zhuJi[i] = 700;
                                zhuJiZhiGong[i] = 1;
                            }
                        }
                    }
                }
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
                for (int i = 23; i < 7 || i == 23; i = (i + 1) % 24) {
                    if (requirement[i] == 0) {
                        shuiXuNeng[i] = 1;
                        xuNeng += shuiXuNengCap;
                        shuiXuNengXu[i] = shuiXuNengCap;
                    } else {
                        zhuJiZhiGong[i] = 1;
                        zhuJi[i] = requirement[i];
                    }
                }
                remain = xuNeng;
            } else {
                /**
                 * 前一天晚上11:00 -第二天早上7:00
                 *每天晚上23：00到早上7:00点如果其中预测数值不等于0，那么对应时间则开启主机直供。
                 * 如果晚上23：00到早上7:00点如果其中预测值等于0，则对应时间开启水蓄能蓄能
                 */
                if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
                    for (int i = 23; i < 7 || i == 23; i = (i + 1) % 24) {
                        if (requirement[i] > 0) {
                            zhuJiZhiGong[i] = 1;
                            zhuJi[i] = requirement[i];
                        }
                    }
                }else {
                    for (int i = 23; i < 7 || i == 23; i = (i + 1) % 24) {
                        if (requirement[i] == 0) {
                            shuiXuNeng[i] = 1;
                            xuNeng += shuiXuNengCap;
                            shuiXuNengXu[i] = shuiXuNengCap;
                        } else {
                            zhuJiZhiGong[i] = 1;
                            zhuJi[i] = requirement[i];
                        }
                    }
                }

                /**
                 * 情况1：周一至周五的17：00-18:00不开水蓄能蓄能 (A > D >=B)
                 * 情况2：周一至周五的17：00-18:00开水蓄能蓄能 (A > B>D )
                 * 情况3：如果能效比比值都比两个电价比A和B都大，则不使用水蓄能这种设备。那么原本上述策略中低谷时间水蓄能全部取消，白天原本是水蓄能放能改为主机直供。（D >= A> B）
                 */

                if (A > D && D >= B) {
                    shuiXuNeng[17] = 0;
                } else if (A > B && B > D) {
                    shuiXuNeng[17] = 1;
                    re = shuiXuNengCap;
                    shuiXuNengXu[17] = shuiXuNengCap;
                } else if (D >= A && D >= B) {
                    for (int i = 0; i < shuiXuNeng.length; i++) {
                        shuiXuNeng[i] = 0;
                        shuiXuNengXu[i] = 0;
                        shuiXuNengFang[i] = 0;
                    }
                    xuNeng = 0;
                    remain = 0;
                }


                /**
                 * 7：00 - 17:00（周一至周五）
                 * 7:00- 8:00不开水蓄能放能，用主机直供供应末端，8：00-12:00再开水蓄能，根据白天的预测需求
                 * 计算当前储存的水蓄能可以用多久，水蓄能用完了再用主机直供，一直到17：00
                 */

                if (requirement[7] != 0) {
                    zhuJiZhiGong[7] = 1;
                    zhuJi[7] = requirement[7];
                }
                remain += xuNeng;
                if (remain > 0) {
                    float sum = 0;
                    float remain1 = remain;
                    float release1 = 0;
                    for (int i = 0; i < 4 && remain1 > 0; i++) {  //默认先开四个小时，如果水蓄能不够，计算放几次能是几次
                        release1 = remain1 * coefficient;
                        sum += release1;
                        remain1 -= release1;
                    }
                    float xuQiu = requirement[8] + requirement[9] + requirement[10];  //电价高峰需求量，默认8--11三个小时是电价高峰
                    if (xuQiu > sum) {
                        int shuiIndex = 8;
                        float release2 = 0;
                        float remain2 = remain;
                        float sum1  = 0;
                        while (remain2>0&&shuiIndex<17){
                            release2 = remain2*coefficient;
                            sum1+=release2;
                            remain2-=release2;
                            shuiIndex++;
                        }
                        if (sum1>=xuQiu){
                            float release5 = 0;
                            int startIndex = 8;
                            for (;startIndex<17&&remain>0;startIndex++){
                                release5 = remain*coefficient;
                                if (startIndex<14) {
                                    shuiXuNeng[startIndex] = 2;
                                }
                                shuiXuNengFang[startIndex] = release5;
                                remain-=release5;
                            }
                        }else {
                            float release6 = 0;
                            for (int i = 8; i <= 11 && remain > 0; i++) {
                                release6 = remain * coefficient;
                                shuiXuNeng[i] = 2;
                                shuiXuNengFang[i] = release6;
                                remain -= release6;
                            }
                            int time = (int) (sum / xuQiu * 180);
                            int j = 8;
                            while (time > 60) {
                                time -= 60;
                                j++;
                            }
                            zhuJiZhiGong[j] = time;
                            zhuJi[j] = xuQiu - sum;
                            for (int i = j + 1; i < 17; i++) {
                                if (requirement[i] > 0) {
                                    zhuJiZhiGong[i] = 1;
                                    zhuJi[i] = requirement[i];
                                }
                            }
                        }

                    } else if (xuQiu < sum) {   //水蓄能放能>8--11时的需求，则满足三个小时电价高峰需求
                        float release3 = 0;
                        int i = 11;
                        for (int index = 8; index <= 10 ; index++) {
                            if (requirement[index] > 0) {
                                shuiXuNeng[index] = 2;
                                release3 = remain * coefficient;
                                remain -= release3;
                                shuiXuNengFang[index] = release3;
                            }
                        }
                        while (requirement[i] == 0) i++;
                        xuQiu += requirement[i];
                        int flag = 0;
                        if (sum > xuQiu) {
                            shuiXuNeng[i] = 2;
                            release3 = remain * coefficient;
                            shuiXuNengFang[i] = release3;
                            remain -= release3;
                        } else if (xuQiu == sum) {
                            shuiXuNeng[i] = 2;
                            release3 = remain * coefficient;
                            shuiXuNengFang[i] = release3;
                            remain -= release3;
                            flag = 1;
                        } else {
                            shuiXuNeng[i] = 2;
                            release3 = remain * coefficient;
                            shuiXuNengFang[i] = release3;
                            remain -= release3;
                            int minute = (int) ((xuQiu - sum) / requirement[i]);
                            zhuJiZhiGong[i] = minute;
                            zhuJi[i] = (float) (xuQiu - sum);
                            flag = -1;
                        }
                        i++;
                        if (flag == 1 || flag == -1) {
                            for (int j = i; j < 17; j++) {
                                if (requirement[j] > 0) {
                                    zhuJiZhiGong[j] = 1;
                                    zhuJi[j] = requirement[j];
                                }
                            }
                        } else {
                            float x = xuQiu;
                            for (int j=i;j<17;j++){
                                x+=requirement[j];
                            }
                            if (sum<x) {
                                int f = 0;
                                for (int j = i; j < 17; j++) {
                                    if (requirement[j] > 0) {
                                        if (f == 0) {
                                            if (remain > 0) {
                                                if (sum + remain * coefficient > requirement[j] + xuQiu) {
                                                    release3 = remain * coefficient;
                                                    sum += release3;
                                                    remain -= release3;
                                                    xuQiu += requirement[j];
                                                    shuiXuNengFang[j] = release3;
                                                } else if (sum + remain * coefficient == requirement[j] + xuQiu) {
                                                    release3 = remain * coefficient;
                                                    sum += release3;
                                                    remain -= release3;
                                                    xuQiu += requirement[j];
                                                    shuiXuNengFang[j] = release3;
                                                    f = 1;
                                                } else {
                                                    release3 = remain * coefficient;
                                                    sum += release3;
                                                    remain -= release3;
                                                    int minute = (int) ((requirement[j] + xuQiu - sum) / requirement[j]);
                                                    shuiXuNengFang[j] = release3;
                                                    zhuJiZhiGong[j] = minute;
                                                    zhuJi[j] = (float) (requirement[j] + xuQiu - sum);
                                                    f = 1;
                                                    remain = 0;
                                                }
                                            }

                                        } else {
                                            zhuJiZhiGong[j] = 1;
                                            zhuJi[j] = requirement[j];
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        float release4 = 0;
                        for (int i = 8; i <= 11 && remain > 0; i++) {
                            release4 = remain * coefficient;
                            shuiXuNeng[i] = 2;
                            shuiXuNengFang[i] = release4;
                            remain -= release4;
                        }
                        for (int j = 10; j < 17; j++) {
                            if (requirement[j] > 0) {
                                zhuJiZhiGong[j] = 1;
                                zhuJi[j] = requirement[j];
                            }
                        }
                    }
                } else {
                    for (int i = 8; i < 17; i++) {
                        if (requirement[i] > 0) {
                            zhuJiZhiGong[i] = 1;
                            zhuJi[i] = requirement[i];
                        }
                    }
                }

            }
            remain += re;
            if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
                remain = 0;
            }


            /**
             * 17:00-23:00无需求
             *
             */

        }


        Map<Integer, List<Integer>> shuiXuNengMap = new HashMap<>();
        Map<Integer, List<Integer>> zhuJiZhiGongMap = new HashMap<>();
        for (int i = 0; i < 24; i++) {
            if (shuiXuNengMap.containsKey(shuiXuNeng[i])) {
                shuiXuNengMap.get(shuiXuNeng[i]).add(i);
            } else {
                List list = new ArrayList();
                list.add(i);
                shuiXuNengMap.put(shuiXuNeng[i], list);
            }
            if (zhuJiZhiGongMap.containsKey(zhuJiZhiGong[i])) {
                zhuJiZhiGongMap.get(zhuJiZhiGong[i]).add(i);
            } else {
                List list = new ArrayList();
                list.add(i);
                zhuJiZhiGongMap.put(zhuJiZhiGong[i], list);
            }
        }
        Iterator<Map.Entry<Integer, List<Integer>>> iterator = shuiXuNengMap.entrySet().iterator();
        List<int[]> res = new ArrayList<>();
        while (iterator.hasNext()) {
            Map.Entry<Integer, List<Integer>> entry = iterator.next();
            System.out.print(entry.getKey() + "  ");
            entry.getValue().forEach(a -> System.out.print(a + " "));
            System.out.println();
            Integer key = entry.getKey();
            List<Integer> entryValueList = entry.getValue();
            Iterator<Integer> integerIterator = entryValueList.iterator();
            int begin = integerIterator.next();
            int end = begin;
            if (!integerIterator.hasNext()) res.add(new int[]{begin, (end + 1) % 24, key});
            while (integerIterator.hasNext()) {
                Integer next = integerIterator.next();
                if (next == end + 1) {
                    end++;
                } else {
                    res.add(new int[]{begin, (end + 1) % 24, key});
                    begin = end = next;
                }
                if (!integerIterator.hasNext()) {
                    res.add(new int[]{begin, (end + 1) % 24, key});
                }
            }
        }

        Iterator<Map.Entry<Integer, List<Integer>>> iterator1 = zhuJiZhiGongMap.entrySet().iterator();
        List<int[]> res1 = new ArrayList<>();
        while (iterator1.hasNext()) {
            Map.Entry<Integer, List<Integer>> entry = iterator1.next();
            System.out.print(entry.getKey() + "  ");
            entry.getValue().forEach(a -> System.out.print(a + " "));
            System.out.println();
            Integer key = entry.getKey();
            List<Integer> entryValueList = entry.getValue();
            Iterator<Integer> integerIterator = entryValueList.iterator();
            int begin = integerIterator.next();
            int end = begin;
            if (!integerIterator.hasNext()) res1.add(new int[]{begin, (end + 1) % 24, key});
            while (integerIterator.hasNext()) {
                Integer next = integerIterator.next();
                if (next == end + 1) {
                    end++;
                } else {
                    res1.add(new int[]{begin, (end + 1) % 24, key});
                    begin = end = next;
                }
                if (!integerIterator.hasNext()) {
                    res1.add(new int[]{begin, (end + 1) % 24, key});
                }
            }
        }

        String nodes = "3,20,36,6,106,95";
        String path = "3#20,3#36,20#36,6#3,3#20,6#3,3#36,106#36,95#36";
        String[] nodesSplit = nodes.split(",");
        String[] pathSplit = path.split(",");
        StringBuilder gongkuang = new StringBuilder();
        StringBuilder xu = new StringBuilder();
        StringBuilder fang = new StringBuilder();
        StringBuilder zhiGong = new StringBuilder();
        List<StrategyOutput> strategyOutputList = new ArrayList<>();
        Calendar yesterday  =Calendar.getInstance();
        yesterday.setTime(now);
        if (shuiXuNengMap.containsKey(1)){
            xu.append("水蓄能  ");
        }
        if (shuiXuNengMap.containsKey(2)){
            fang.append("水蓄能  ");
        }
        int endFang = 0;
        int startFang = 0;
        int m = 0;
        int[] v1 = null,v2 = null,v3 = null,v4 =null,v5=null,v6=null;
        List<int[]> res3 = new ArrayList<>();
        List<int[]> res4 = new ArrayList<>();
        for (int[] a:res){
            if (a[0]==23&&a[1]==0&&a[2]==1){
                v1 = new int[]{a[0],a[1],a[2]};
            }else if (a[0]==23&&a[1]==0&&a[2]==2){
                v3 = new int[]{a[0],a[1],a[2]};
            }else if (a[0]==0&&a[2]==1) {
                v2 = new int[]{a[0],a[1],a[2]};
            }else if (a[0]==0&&a[2]==2) {
                v4 = new int[]{a[0],a[1],a[2]};
            }else {
                res3.add(new int[]{a[0],a[1],a[2]});
            }
        }
        if (v1!=null&&v2!=null){
            res3.add(new int[]{v1[0],v2[1],v1[2]});
        }else if (v1!=null){
            res3.add(v1);
        }else if (v2!=null){
            res3.add(v2);
        }
        if (v3!=null&&v4!=null){
            res3.add(new int[]{v3[0],v4[1],v3[2]});
        }else if (v3!=null){
            res3.add(v3);
        }else if (v4!=null){
            res3.add(v4);
        }


        for (int[] a:res1){
            if (a[0]==23&&a[1]==0){
                v5 = new int[]{a[0],a[1],a[2]};
            }else if (a[0]==0){
                v6 = new int[]{a[0],a[1],a[2]};
            }else {
                res4.add(new int[]{a[0],a[1],a[2]});
            }
        }


        if (v5!=null&&v6!=null){
            res4.add(new int[]{v5[0],v6[1],v5[2]});
        }else if (v5!=null){
            res4.add(v5);
        }else if (v6!=null){
            res4.add(v6);
        }

        for (int[] a : res3) {
            System.out.print("[" + a[0] + "," + a[1] + "," + a[2] + "]");
            if (a[2] == 1) {
                xu.append(a[0] + ":00~" + a[1] + ":00   ");
                if (a[0]>a[1]){
                    String startTime = new SimpleDateFormat("yyyy-MM-dd").format(yesterday.getTime()) + " " + a[0] + ":00:00";
                    String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + a[1] + ":00:00";
                    StrategyOutput so = new StrategyOutput();
                    so.setCode(2);
                    so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                    so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                    so.setInfo(a[0] + ":00~" + a[1] + ":00蓄能");
                    strategyOutputList.add(so);
                }else {
                    String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + a[0] + ":00:00";
                    String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + a[1] + ":00:00";
                    StrategyOutput so = new StrategyOutput();
                    so.setCode(2);
                    so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                    so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                    so.setInfo(a[0] + ":00~" + a[1] + ":00蓄能");
                    strategyOutputList.add(so);
                }
            } else if (a[2] == 2) {
                startFang = a[0];
                endFang = a[1];
            } else if (a[2] != 0) {
                m = a[2];
            }
        }
        if (startFang!=endFang) {
            if (m == 0) {
                fang.append(startFang + ":00~" + endFang + ":00   ");
                String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + startFang + ":00:00";
                String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + endFang + ":00:00";
                StrategyOutput so = new StrategyOutput();
                so.setCode(3);
                so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                so.setInfo(startFang + ":00~" + endFang + ":00放能");
                strategyOutputList.add(so);
            } else {
                fang.append(startFang + ":00~" + endFang + ":" + m + "   ");
                String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + startFang + ":00:00";
                String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + endFang + ":"+m+":00";
                StrategyOutput so = new StrategyOutput();
                so.setCode(3);
                so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                so.setInfo(startFang + ":00~" + endFang + ":" + m +"放能");
                strategyOutputList.add(so);
            }

        }

        if (xu.length() == 0) {
            StringBuffer nodesStr = new StringBuffer();
            StringBuffer pathStr = new StringBuffer();
            for (int i = 0; i < nodesSplit.length; i++) {
                if (nodesSplit[i].indexOf("20") == -1) {
                    nodesStr.append(nodesSplit[i] + ",");
                }
            }
            for (int i = 0; i < pathSplit.length; i++) {
                if (pathSplit[i].indexOf("20") == -1) {
                    pathStr.append(pathSplit[i] + ",");
                }
            }
            if (nodesStr.lastIndexOf(",") == nodesStr.length() - 1) {
                nodesStr.deleteCharAt(nodesStr.length() - 1);
            }
            if (pathStr.lastIndexOf(",") == pathStr.length() - 1) {
                pathStr.deleteCharAt(pathStr.length() - 1);
            }
            nodesSplit = nodesStr.toString().split(",");
            pathSplit = pathStr.toString().split(",");
        } else {
            xu.append("蓄能");
        }
        if (fang.length() != 0) {
            fang.append("放能");
        }
        if(zhuJiZhiGongMap.containsKey(1)){
            zhiGong.append("主机");
        }
        int mi = 0;
        int startZhiGong = 0;
        int endZhiGong = 0;
        for (int[] a : res4) {
            System.out.print("[" + a[0] + "," + a[1] + "," + a[2] + "]");
            if (a[2] == 1) {
                if (a[0] < 17 && a[0] >= 8) {
                    startZhiGong = a[0];
                    endZhiGong = a[1];
                } else {
                        zhiGong.append(a[0] + ":00~" + a[1] + ":00   ");
                    if (a[0]>a[1]){
                        float sum = zhuJi[a[0]];
                        int count = 1;
                        for (int i = 0; i < a[1]; i++) {
                            sum+=zhuJi[i];
                            count++;
                        }
                        float average = sum / count;
                        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(yesterday.getTime()) + " " + a[0] + ":00:00";
                        String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + a[1] + ":00:00";
                        StrategyOutput so = new StrategyOutput();
                        so.setCode(1);
                        so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                        so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                        so.setInfo(a[0] + ":00~" + a[1] + ":00直供");
                        so.setPower(average);
                        strategyOutputList.add(so);
                    }else {
                        float sum = 0;
                        int count = 0;
                        for (int i = a[0]; i < a[1]; i++) {
                            sum+=zhuJi[i];
                            count++;
                        }
                        float average = sum / count;
                        String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + a[0] + ":00:00";
                        String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + a[1] + ":00:00";
                        StrategyOutput so = new StrategyOutput();
                        so.setCode(1);
                        so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                        so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                        so.setInfo(a[0] + ":00~" + a[1] + ":00直供");
                        so.setPower(average);
                        strategyOutputList.add(so);
                    }

                }
            } else if (a[2] != 0) {
                mi = a[2];
            }
        }
        if (startZhiGong!=endZhiGong) {
            float sum = 0;
            int count = 0;
            for (int i = startZhiGong; i < endZhiGong; i++) {
                sum+=zhuJi[i];
                count++;
            }
            float average = sum / count;
            if (mi == 0) {
                zhiGong.append(startZhiGong + ":00~" + endZhiGong + ":00   ");
                String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + startZhiGong + ":00:00";
                String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + endZhiGong + ":00:00";
                StrategyOutput so = new StrategyOutput();
                so.setCode(1);
                so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                so.setInfo(startFang + ":00~" + endFang + ":00直供");
                so.setPower(average);
                strategyOutputList.add(so);
            } else {
                zhiGong.append((startZhiGong - 1) + ":" + mi + "~" + endZhiGong + ":00   ");
                String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + (startZhiGong - 1) + ":"+mi+":00";
                String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + endZhiGong + ":00:00";
                StrategyOutput so = new StrategyOutput();
                so.setCode(1);
                so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
                so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
                so.setInfo((startZhiGong - 1) + ":" + mi + "~" + endFang + ":00直供");
                so.setPower(average);
                strategyOutputList.add(so);
            }
        }
        if (zhiGong.length() != 0) {
            zhiGong.append("开启直供");
        } else {
            StringBuffer pathStr = new StringBuffer();
            for (int i = 0; i < pathSplit.length; i++) {
                if (pathSplit[i].indexOf("3#36") == -1) {
                    pathStr.append(pathSplit[i] + ",");
                }
            }
            if (pathStr.lastIndexOf(",") == pathStr.length() - 1) {
                pathStr.deleteCharAt(pathStr.length() - 1);
            }
            pathSplit = pathStr.toString().split(",");
        }
        if (xu.length()>0) {
            gongkuang.append(xu.toString() + ",");
        }
        if (fang.length()>0) {
            gongkuang.append(fang.toString() + ",");
        }
        if (zhiGong.length()>0) {
            gongkuang.append(zhiGong.toString()+",");
        }
        if (solarIsOpen(now)) {
            gongkuang.append("太阳能11:00~15:00开启");
            String startTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + "11:00:00";
            String endTime = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()) + " " + "15:00:00";
            StrategyOutput so = new StrategyOutput();
            so.setCode(4);
            so.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
            so.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
            so.setInfo("11:00~15:00开启太阳能");
            strategyOutputList.add(so);
            for (int i = 11;i<=15;i++){
                solar[i] = 32;
            }
        } else {
            StringBuffer nodesStr = new StringBuffer();
            StringBuffer pathStr = new StringBuffer();
            for (int i = 0; i < nodesSplit.length; i++) {
                if (nodesSplit[i].indexOf("95") == -1) {
                    nodesStr.append(nodesSplit[i] + ",");
                }
            }
            for (int i = 0; i < pathSplit.length; i++) {
                if (pathSplit[i].indexOf("95") == -1) {
                    pathStr.append(pathSplit[i] + ",");
                }
            }
            if (nodesStr.lastIndexOf(",") == nodesStr.length() - 1) {
                nodesStr.deleteCharAt(nodesStr.length() - 1);
            }
            if (pathStr.lastIndexOf(",") == pathStr.length() - 1) {
                pathStr.deleteCharAt(pathStr.length() - 1);
            }
            nodesSplit = nodesStr.toString().split(",");
            pathSplit = pathStr.toString().split(",");
        }

        String gk = gongkuang.toString();
        if (gk.lastIndexOf(",")==gk.length()-1){
            gk = gk.substring(0, gk.length() - 1);
        }

        Map<String, Object> ans = new HashMap();
        ans.put("path", pathSplit);
        ans.put("node", nodesSplit);
        ans.put("gongkuang",gk.split(","));
        ans.put("zhuJi",zhuJi);
        ans.put("shuiXuNengFang",shuiXuNengFang);
        ans.put("shuiXuNengXu",shuiXuNengXu);
        ans.put("solar",solar);
        ans.put("remain",remain);
        ans.put("rc", "0");
        ans.put("strategyOutputList",strategyOutputList);
        for (int i = 0; i < zhuJi.length; i++) {
            System.out.print(zhuJi[i] + " ");
        }
        System.out.println();
        for (int j = 0; j < shuiXuNengFang.length; j++) {
            System.out.print(shuiXuNengFang[j] + " ");
        }
        System.out.println();
        for (int i = 0; i < shuiXuNengXu.length; i++) {
            System.out.print(shuiXuNengXu[i] + " ");
        }
        System.out.println();
        for (int i = 0; i < solar.length; i++) {
            System.out.print(solar[i] + " ");
        }
        System.out.println();
        System.out.println("remain:"+remain);
        return ans;
    }

    private boolean solarIsOpen(Date now) throws IOException, ParseException {
        List<String[]> readCsv = ReadCsv.readCsv("/home/power/uploadfile/aj/data/prehour.csv");
        //List<String[]> readCsv = ReadCsv.readCsv("C:\\Users\\DragonGao\\AppData\\Roaming\\Notepad++\\plugins\\config\\NppFTP\\Cache\\root@49.234.228.157\\home\\power\\uploadfile\\aj\\data\\prehour.csv");
        //List<String[]> readCsv = ReadCsv.readCsv("F:\\anjie\\testdp.csv");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DATE, 1);
        Date date = calendar.getTime();
        List<String> list = new ArrayList<>();
        for (String[] strs : readCsv) {
            String dateStr = strs[0];
            dateStr = dateStr.split(" ")[0];
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            Date date1 = simpleDateFormat.parse(dateStr);
            if (DateUtils.isSameDay(date1, date)) {
                list.add(strs[4]);
            }
        }
        int count = 0;
        for (String s : list) {
            if ("Sunny.".equals(s)) {
                count++;
            }
        }
        if (count >= 1)
            return true;
        else return false;
    }
}